<?php

/**
 * This is the model class for table "periodo".
 *
 * The followings are the available columns in table 'periodo':
 * @property integer $id
 * @property string $ano
 * @property boolean $fechado
 * @property string $inicio_inscricao
 * @property string $fim_inscricao
 * @property integer $polo_id
 *
 * The followings are the available model relations:
 * @property Turma[] $turmas
 */
class Periodo extends CActiveRecord {

    public static function addPeriodo($polo_id) {

        date_default_timezone_set('America/Los_Angeles');
        $initial_date = date('d/m/Y');
        $final_date = Periodo::add_date($initial_date, 0, 1, 0);
        $year = date("Y");
        $query = "INSERT INTO periodo (ano, fechado, inicio_inscricao, fim_inscricao, polo_id ) VALUES ('$year', '0','$initial_date','$final_date','$polo_id');";
        Yii::app()->db->createCommand($query)->execute();
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'periodo';
    }
    
    public static function closePeriodos() {
            $periodos = Periodo::model()->findAll();
            $data = date('d-m-Y');
            $today = strtotime($data);
            foreach( $periodos as $periodo) {
                $current = strtotime($periodo->fim_inscricao);
                if( $current < $today ) {
                    $periodo->fechado = 1;
                    $periodo->save();
                } else {
                    $periodo->fechado = 0;
                    $periodo->save();
                }
            }
                
        }
    
    public static function semPeriodosAbertos($polo_id) {
            $periodos = Periodo::model()->findAllByAttributes(array('polo_id'=>$polo_id));
            foreach( $periodos as $periodo) {
                if($periodo->fechado == 0) {
                    return 0;
                }
            }
            return 1;
        }

    public static function add_date($givendate, $day, $mth, $yr) {
        $cd = strtotime($givendate);
        $newdate = date('d-m-Y', mktime(
                        date('m', $cd) + $mth, date('d', $cd) + $day, date('Y', $cd) + $yr));
        return $newdate;
    }

    public static function subtractDate($date1, $date2) {
        $datetime1 = strtotime($date1);
        $datetime2 = strtotime(date2);

        $secs = $datetime2 - $datetime1; // == <seconds between the two times>
        $days = $secs / 86400;
        return $days;
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('ano, inicio_inscricao, fim_inscricao, polo_id', 'required'),
            array('polo_id', 'numerical', 'integerOnly' => true),
            array('fechado', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, ano, fechado, inicio_inscricao, fim_inscricao, polo_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'turmas' => array(self::HAS_MANY, 'Turma', 'periodo_id'),
        );
    }
    
    public function deleteData() {
        $this->delete();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'ano' => 'Ano',
            'fechado' => 'Fechado',
            'inicio_inscricao' => 'Inicio Inscricao',
            'fim_inscricao' => 'Fim Inscricao',
            'polo_id' => 'Polo',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search($parameter, $user_id) {
        // @todo Please modify the following code to remove attributes that should not be searched.
    	
        $criteria = new CDbCriteria;
        if($user_id != 1) {
        	
        	$criteria->addCondition('polo_id = :polo_id');
        	$criteria->params = array(':polo_id' => $parameter);
        }
        $criteria->compare('id', $this->id);
        $criteria->compare('ano', $this->ano, true);
        $criteria->compare('fechado', $this->fechado);
        $criteria->compare('inicio_inscricao', $this->inicio_inscricao, true);
        $criteria->compare('fim_inscricao', $this->fim_inscricao, true);
        $criteria->compare('polo_id', $this->polo_id);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Periodo the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

}
